<template>
	<view>
		<scroll-view scroll-y class="box">
			<view class="item" v-for="item in lanMes" @click="connectLan(item)">
				<view>
					<text>id: {{ item.deviceId }}</text>
				</view>
				<view>
					<text>name: {{ item.name }}</text>
				</view>
			</view>
		</scroll-view>
		<button @click="openLan()">1 初始化蓝牙</button>
		<button @click="sourceLan()">2 搜索附近蓝牙设备</button>
		<button @click="getServiceId()">3 获取蓝牙服务</button>
		<!-- <button @click="getCharacteristics">4 获取特征值</button> -->
		<button @click="notify()">4 开启消息监听</button>
		<!-- <button @click="send">6 发送数据</button> -->
		<!-- <button @click="read">7 读取数据</button> -->
		<button @click="closeLan()">5 断开蓝牙连接</button>
		<button @click="jiaohu()">6 蓝牙交互</button>
		<view class="msgX">
			<view class="msgTxt">
				监听到的内容：{{ message }}
			</view>
			<!-- <view class="msgHex"> -->
				<!-- 监听到的内容（十六进制）：{{ messageHex }} -->
			<!-- </view> -->
		</view>
		​
	</view>
</template>
​
<script>
	import store from '@/store/index.js'; //需要引入store
	export default {
		data() {
			return {
				lanMes: [],
				deviceId: '',
				serviceId: '',
				characteristicId1: '',
				characteristicId2: '',
				message: '',
				messageList: [],
			}
		},
		onLoad() {
		
		},
		methods: {
			jiaohu() {
				store.commit("setCharacteristicId", this.characteristicId2)
				store.commit("setDeviceId", this.deviceId)
				store.commit("setServiceId", this.serviceId)
				uni.navigateTo({
					url: '../BLEmsg/BLEmsg'
				})
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			hexCharCodeToStr(hexCharCodeStr) {
				var trimedStr = hexCharCodeStr.trim();
				var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
				var len = rawStr.length;
				if (len % 2 !== 0) {
					alert("存在非法字符!");
					return "";
				}
				var curCharCode;
				var resultStr = [];
				for (var i = 0; i < len; i = i + 2) {
					curCharCode = parseInt(rawStr.substr(i, 2), 16);
					resultStr.push(String.fromCharCode(curCharCode));
				}
				return resultStr.join("");
			},
			openLan() {
				uni.openBluetoothAdapter({
					success: (res) => {
						console.log("初始化蓝牙成功")
						uni.showToast({
							title: '初始化蓝牙成功'
						})
					},
					fail: (res) => {
						console.log("初始化蓝牙失败")
						uni.showToast({
							title: '初始化蓝牙失败'
						})
					}
				})
			},
			sourceLan() {
				// this.lanMes = []
				let that = this
				uni.startBluetoothDevicesDiscovery({
					success: function(res) {
						console.log('搜索设备---')
						uni.onBluetoothDeviceFound(function(res) {
							if ( res.devices[0].name != "") {
								console.log(res.devices[0])
								that.lanMes.push(res.devices[0])
							}
						})
					},
				})
			},
			connectLan(e) {
				this.deviceId = e.deviceId
				console.log(this.deviceId);
				let that = this
				uni.createBLEConnection({
					deviceId: that.deviceId,
					success: (res) => {
						// console.log('连接蓝牙成功')
						// uni.showToast({
						// 	title: '连接蓝牙成功'
						// })
						// that.stopDiscovery()
						that.connectLan(e)
					},
					fail: (res) => {
						that.stopDiscovery()
						console.log(res)
						uni.showToast({
							title: '蓝牙已连接',
						})
					}
				})
			},
			//停止搜索
			stopDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						console.log('停止搜索成功')
						console.log(res)
					},
					fail(err) {
						console.log('停止搜索失败')
						console.error(err)
					}
				})
			},
			//获取服务
			getServiceId() {
				let that = this
				uni.showLoading({
					title: '加载中'
				});
				setTimeout(() => {
					uni.getBLEDeviceServices({
						deviceId: that.deviceId,
						success(res) {
							console.log(res)
							that.serviceId = res.services[0].uuid
							console.log(that.serviceId)
							setTimeout(() => {
								that.getBLEDeviceCharacteristics(that.deviceId, that.serviceId)
							}, 1000)
							uni.hideLoading();
							uni.showToast({
								title: '获取服务成功'
							})
						},
						fail(err) {
							uni.hideLoading();
							console.error(err)
							uni.showToast({
								title: '获取服务失败',
								icon: 'error'
							})
						}
					})
				}, 2000)
			},
		
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				let that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: deviceId,
					serviceId: serviceId,
					success: (res) => {
						console.log(res)
						that.characteristicId1 = res.characteristics[0].uuid;
						that.characteristicId2 = res.characteristics[1].uuid;
						console.log(that.characteristicId1)
						console.log(that.characteristicId2);
					},
					fail(res) {
						console.error('获取蓝牙设备特征值失败(getBLEDeviceCharacteristics)', res)
					}
				})
			},
			//消息监听
			notify() {
				let that = this
				uni.notifyBLECharacteristicValueChange({
					deviceId: that.deviceId,
					serviceId: that.serviceId,
					characteristicId: that.characteristicId1,
					state: true, //是否启用notify通知
					success(res) {
						console.log(res)
						uni.showToast({
							title: '已开启监听'
						})
						that.listenValueChange()
					},
					fail(err) {
						console.error(err)
						uni.showToast({
							title: '监听失败',
							icon: 'error'
						})
					}
				})
			},
			listenValueChange() {
				uni.onBLECharacteristicValueChange(res => {
					console.log(res)
					let resHex = this.ab2hex(res.value)
					//console.log(resHex)
					let msg = this.hexCharCodeToStr(resHex)
					console.log(String(msg))
					this.message = String(msg)
					this.messageList.push(JSON.parse(msg))
				})
			},
			//读取数据
			read() {
				uni.readBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceId,
					characteristicId: this.characteristicId,
					success(res) {
						console.log(res)
						uni.showToast({
							title: 'read指令发送成功'
						})
					},
					fail(err) {
						console.error(err)
						uni.showToast({
							title: 'read指令发送失败',
							icon: 'error'
						})
					}
				})
			},
			closeLan() {
				uni.closeBLEConnection({
					deviceId: this.deviceId,
					success(res) {
						this.deviceId = ''
						uni.showToast({
							title: '断开成功'
						})
						console.log(res, "断开成功")
					}
				})
			}
		},
	}
</script>
​
<style>
	.box {
		width: 98%;
		height: 400rpx;
		box-sizing: border-box;
		margin: 0 auto 20rpx;
		border: 2px solid dodgerblue;
	}

	.item {
		box-sizing: border-box;
		padding: 10rpx;
		border-bottom: 1px solid #ccc;
	}

	.msgX {
		border: 2px solid seagreen;
		width: 98%;
		margin: 10rpx auto;
		box-sizing: border-box;
		padding: 20rpx;
	}

	.msgX .msgTxt {
		margin-bottom: 20rpx;
	}


	button {
		margin-bottom: 20rpx;
	}
</style>
